﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Tizer.Core;
using Tizer.Core.Enums;
using Tizer.Core.Helpers;
using Tizer.Core.Repository;
using Tizer.Utilities;
using Tizer.Web.Backoffice.Controls;

namespace Tizer.Web.Backoffice
{
    /// <summary>
    /// Добавление нового аккаунта
    /// </summary>
    public partial class AccountAdd : AdminBasePage
    {
        /// <summary>
        /// Инициализация страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
              BindCountryList();
              BindAccountType();

              var emptyItem = new ListItem { Text = StrNotChoosed, Value = "0" };
              ddlCity.Items.Add(emptyItem);
        }

        /// <summary>
        /// Загрузка страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.SetPageTitle();
        }

        /// <summary>
        /// Добавить новый аккаунт
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Add(object sender, EventArgs e)
        {
            if (Page.IsPostBack && Page.IsValid)
            {
                using (var accountRepository = new AccountRepository())
                {
                    string passwordSalt = PasswordHelper.GeneratePasswordSalt();
                    string message = string.Empty;

                    var account = new Account
                                      {
                                          AccountType = EnumMetadataConverter.NumToEnum<AccountType>(ddlAccountType.SelectedIndex),
                                          Address = txtAddress1.Text,
                                          Address2 = txtAddress2.Text,
                                          Company = txtCompany.Text,
                                          CreatedDate = DateTime.Now,
                                          Description = txtDescription.Text,
                                          Email = txtEmail.Text,
                                          Fax = Convert.ToInt32(txtFax.Text),
                                          Phone = Convert.ToInt32(txtPhone.Text),
                                          Phone2 = Convert.ToInt32(txtPhone2.Text),
                                          ICQ = Convert.ToInt32(txtICQ.Text),
                                          MobilePhone = Convert.ToInt32(txtPhoneMobile.Text),
                                          IsActive = chkActive.Checked,
                                          IsApproved = chkActive.Checked,
                                          LastLoginDate = DateTime.Now,
                                          LastLockedOutDate = DateTime.Now,
                                          PasswordSalt = passwordSalt,
                                          PasswordHash = PasswordHelper.HashPassword(txtPassword1.Text, passwordSalt),
                                          Website = txtWebsite.Text,
                                          PublicEmail = txtPublicEmail.Text,
                                          Login = txtLogin.Text,
                                          PostalCode = Convert.ToInt32(txtPostalCode.Text)
                                      };


                    if (ddlCountry.SelectedItem.Value != "0")
                        account.CountryID = Convert.ToInt32(ddlCountry.SelectedItem.Value);


                    if (ddlCity.SelectedItem.Value != "0")  
                       account.CityID = Convert.ToInt32(ddlCity.SelectedItem.Value);

                    if ((LogoUpload.ImageContent != null || MapUpload.ImageContent != null) && account != null)
                    {
                        using(var imageTypeRepository = new ImageTypeRepository(accountRepository.Context))
                        {
                            ImageType logoImageType = imageTypeRepository.GetByCode("LOGO");
                            ImageType largeMapImageType = imageTypeRepository.GetByCode("COMPANY_MAP");

                            using (var imageRepository = new ImageRepository(accountRepository.Context))
                            {
                                if (LogoUpload.ImageContent != null)
                                {
                                    Tizer.Core.Image logoImage = new Core.Image
                                    {
                                        ImageContent = LogoUpload.ImageContent,
                                        ImageType = logoImageType,
                                        Date = DateTime.Now
                                    };
                                    if (logoImage != null)
                                    {
                                        account.ImageLogo = logoImage;
                                        imageRepository.Add(logoImage);
                                    }
                                }
                                if (MapUpload.ImageContent != null)
                                {
                                    Tizer.Core.Image mapImage = new Core.Image
                                    {
                                        ImageContent = MapUpload.ImageContent,
                                        ImageType = largeMapImageType,
                                        Date = DateTime.Now
                                    };
                                    if (mapImage != null)
                                    {
                                        account.ImageMap = mapImage;
                                        imageRepository.Add(mapImage);
                                    }
                                }
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(message))
                    {
                        accountRepository.Add(account);
                        accountRepository.SaveChanges();

                        tizerMessage.SetMessage("Сообщение", "Акканут добавлен. Можете добавить следующий");
                    }
                    else
                    {
                        tizerMessage.SetMessage("Ошибка", message, MessageType.Error);
                    }
                }
            }
        }

        /// <summary>
        /// Заполнение списка стран
        /// </summary>
        private void BindCountryList()
        {
            var emptyItem = new ListItem {Text = StrNotChoosed, Value = "0"};
            ddlCountry.Items.Add(emptyItem);

            using (var countryRepository = new CountryRepository())
            {
                var countries = countryRepository.GetAll();
                if (countries != null)
                {
                    foreach (var country in countries)
                    {
                        var item = new ListItem { Text = country.Name, Value = country.ID.ToString() };
                        ddlCountry.Items.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// Заполнение списка регионов/областей
        /// </summary>
        private void BindCityList(int countryId)
        {
            ddlCity.Items.Clear();

            var emptyItem = new ListItem { Text = StrNotChoosed, Value = "0" };
            ddlCity.Items.Add(emptyItem);


            using (var cityRepository = new CityRepository())
            {
                var cities = cityRepository.GetQuery().Where(x => x.Country.ID == countryId);
                if ( cities!= null)
                {
                    foreach (var city in cities)
                    {
                        var item = new ListItem { Text = city.Name, Value = city.ID.ToString() };
                        ddlCity.Items.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// Выбор страны пользователем
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DdlCountryIndexChange(object sender, EventArgs e)
        {
            int country = 0;
            int.TryParse(ddlCountry.SelectedItem.Value, out country);
            BindCityList(country);
        }

       /// <summary>
       /// Заполнение дропдауна с аккаунтами
       /// </summary>
       private void BindAccountType()
       {
           Dictionary<int, string> accountTypeList = EnumMetadataConverter.GetListItems(typeof(AccountType));
           foreach (var type in accountTypeList)
           {
               if (type.Key != 0)
               ddlAccountType.Items.Add(new ListItem {Value = type.Key.ToString(), Text = type.Value});
           }
       }

        /// <summary>
        /// Очитска формы
        /// </summary>
        public void Clear()
        {
            txtAddress1.Text = string.Empty;
            txtAddress2.Text = string.Empty;
            txtCompany.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtFax.Text = string.Empty;
            txtICQ.Text = string.Empty;
            txtLogin.Text = string.Empty;
            txtPassword1.Text = string.Empty;
            txtPassword2.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtPhone2.Text = string.Empty;
            txtPhoneMobile.Text = string.Empty;
            txtPostalCode.Text = string.Empty;
            txtPublicEmail.Text = string.Empty;
            txtWebsite.Text = string.Empty;
        }
    }
}